﻿namespace EAL
{
    using System;
    using System.Configuration;
    using System.Globalization;
    using System.IO;
    using System.Reflection;
    using System.Windows;
    using System.Windows.Markup;
    using System.Windows.Threading;
    using EAL.Database;
    using EAL.Models;

    /// <summary>
    /// Interaktionslogik für "App.xaml"
    /// </summary>
    public partial class App : Application
    {
        private String logFile;
        public String LogFile
        {
            get
            {
                if (this.logFile == null)
                {
                    this.logFile = String.Format(@"{0}\{1}", new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.ToString(), ConfigurationManager.AppSettings["LogFile"]);
                }
                return this.logFile;
            }
        }

        public bool IsShutdowning  { get; protected set; }


        private void Application_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            using (StreamWriter sw = new StreamWriter(this.LogFile, true))
            {
                sw.WriteLine(String.Format("{0}: {1}", DateTime.Now.ToString(), e.Exception.ToString()));
            }
            SendError errWin = new SendError();
            errWin.setMessage(e.Exception);

            errWin.Show();
            e.Handled = true;
        }


        private void Application_Startup(object sender, StartupEventArgs e)
        {
            // UI auf aktuelle Kultur einstellen 
            FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));

            this.ShutdownMode = ShutdownMode.OnExplicitShutdown;
            DbContext dbContext = Application.Current.TryFindResource("DbContext") as DbContext;

            if (dbContext != null)
            {
                Options ops = dbContext.Options.Find(Environment.MachineName);

                if (null != ops && ops.LicenseAccepted)
                    return;
            }

            Window licenseWindow = new AcceptLicence();
            if (licenseWindow.ShowDialog().Value)
            {
                dbContext.Options.Add(new Options() { LicenseAccepted = true, MachineName = Environment.MachineName });
                dbContext.SaveChanges();
                licenseWindow.Close();
            }
            else
            {
                this.IsShutdowning = true;
                this.Shutdown();
            }
        }
    }
}
